from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.template.loader import render_to_string
from django.views.decorators.http import require_http_methods, require_GET, require_POST
from django.http.response import JsonResponse, HttpResponse
from .forms import BaseInformationForm, EducationExperienceForm, WorkExpericenceForm, AwardForm, SkillForm, ProjectForm, \
    JobIntentionForm
from .models import BaseInformationModel, EducationExperienceModel, WorkExperienceModel, AwardModel, SkillModel, \
    ProjectModel, JobIntentionModel

from weasyprint import HTML
# Create your views here.


@require_http_methods(["GET", "POST"])
@login_required(login_url='/login/')  # 如果用户未登录，重定向到登录页面
def base_information(request):
    if request.method == 'GET':
        try:
            info = BaseInformationModel.objects.get(user=request.user)
            form = {
                'name': info.name,
                'gender': info.gender,
                'birthday': info.birthday.strftime('%Y-%m-%d'),
                'phone': info.phone,
                'email': info.email,
                'location': info.location,
                'personal_description': info.personal_description,
            }
        except:
            form = {
                'name': '',
                'gender': '',
                'birthday': '',
                'phone': '',
                'email': '',
                'location': '',
                'personal_description': '',
            }
        return render(request, 'resume_manage/base_information.html', {'form': form})
    else:
        form = BaseInformationForm(request.POST)
        # 获取表单数据
        if form.is_valid():
            name = form.cleaned_data.get('name')
            gender = form.cleaned_data.get('gender')
            birthday = form.cleaned_data.get('birthday')
            phone = form.cleaned_data.get('phone')
            email = form.cleaned_data.get('email')
            location = form.cleaned_data.get('location')
            personal_description = form.cleaned_data.get('personal_description')
            # 正确使用update_or_create的方式
            BaseInformationModel.objects.update_or_create(
                user=request.user,  # 查询条件：根据用户查找记录
                defaults={  # 如果找到记录则更新这些字段，如果没找到则创建新记录
                    'name': name,
                    'gender': gender,
                    'birthday': birthday,
                    'phone': phone,
                    'email': email,
                    'location': location,
                    'personal_description': personal_description
                }
            )
            return JsonResponse({'code': 200, 'message': '简历信息保存成功'})
        else:
            print(form.errors)
            return JsonResponse({'code': 400, 'message': '简历信息保存失败'})


def education_experience(request):
    if request.method == 'GET':
        try:
            info = EducationExperienceModel.objects.get(user=request.user)
            form = {
                'school': info.school,
                'major': info.major,
                'degree': info.degree,
                'start_date': info.start_date.strftime('%Y-%m-%d'),
                'end_date': info.end_date.strftime('%Y-%m-%d'),
                'gpa': info.gpa,
                'description': info.description,
            }
        except:
            form = {
                'school': '',
                'major': '',
                'degree': '',
                'start_date': '',
                'end_date': '',
                'gpa': '',
                'description': '',
            }
        return render(request, 'resume_manage/education_experience.html', {'form': form})
    else:
        form = EducationExperienceForm(request.POST)
        if form.is_valid():
            school = form.cleaned_data.get('school')
            major = form.cleaned_data.get('major')
            degree = form.cleaned_data.get('degree')
            start_date = form.cleaned_data.get('start_date')
            end_date = form.cleaned_data.get('end_date')
            gpa = form.cleaned_data.get('gpa')
            description = form.cleaned_data.get('description')
            EducationExperienceModel.objects.update_or_create(
                user=request.user,
                defaults={

                    'school': school,
                    'major': major,
                    'degree': degree,
                    'start_date': start_date,
                    'end_date': end_date,
                    'gpa': gpa,
                    'description': description
                }
            )
            return JsonResponse({'code': 200, 'message': '简历信息保存成功'})
        else:
            print(form.errors)
            return JsonResponse({'code': 400, 'message': '简历信息保存失败'})


def work_experience(request):
    if request.method == 'GET':
        try:
            info = WorkExperienceModel.objects.get(user=request.user)
            form = {
                'company_name': info.company_name,
                'position': info.position,
                'department': info.department,
                'start_date': info.start_date.strftime('%Y-%m-%d'),
                'end_date': info.end_date.strftime('%Y-%m-%d'),
                'responsibilities': info.responsibilities,
            }
        except:
            form = {
                'company_name': '',
                'position': '',
                'department': '',
                'start_date': '',
                'end_date': '',
                'responsibilities': '',
            }
        return render(request, 'resume_manage/work_experience.html', {'form': form})
    else:
        # 处理POST请求
        form = WorkExpericenceForm(request.POST)
        if form.is_valid():
            company = form.cleaned_data.get('company')
            position = form.cleaned_data.get('position')
            department = form.cleaned_data.get('department')
            start_date = form.cleaned_data.get('start_date')
            end_date = form.cleaned_data.get('end_date')
            responsibilities = form.cleaned_data.get('responsibilities')
            WorkExperienceModel.objects.update_or_create(
                user=request.user,
                defaults={
                    'company_name': company,
                    'position': position,
                    'department': department,
                    'start_date': start_date,
                    'end_date': end_date,
                    'responsibilities': responsibilities
                }
            )
            return JsonResponse({'code': 200, 'message': '简历信息保存成功'})
        else:
            print(form.errors)
            return JsonResponse({'code': 400, 'message': '简历信息保存失败'})


def project_experience(request):
    if request.method == 'GET':
        try:
            info = ProjectModel.objects.get(user=request.user)
            form = {
                'project_name': info.project_name,
                'project_role': info.project_role,
                'start_date': info.start_date.strftime('%Y-%m-%d'),
                'end_date': info.end_date.strftime('%Y-%m-%d'),
                'project_description': info.project_description,
                'responsibilities': info.responsibilities,
                'technologies': info.technologies,
            }
        except:
            form = {
                'project_name': '',
                'project_role': '',
                'start_date': '',
                'end_date': '',
                'project_description': '',
                'responsibilities': '',
                'technologies': '',
            }
        return render(request, 'resume_manage/project_experience.html', {'form': form})
    else:
        # 处理POST请求
        form = ProjectForm(request.POST)
        if form.is_valid():
            project_name = form.cleaned_data.get('project_name')
            project_role = form.cleaned_data.get('project_role')
            start_date = form.cleaned_data.get('start_date')
            end_date = form.cleaned_data.get('end_date')
            project_description = form.cleaned_data.get('project_description')
            responsibilities = form.cleaned_data.get('responsibilities')
            technologies = form.cleaned_data.get('technologies')
            ProjectModel.objects.update_or_create(
                user=request.user,
                defaults={
                    'project_name': project_name,
                    'project_role': project_role,
                    'start_date': start_date,
                    'end_date': end_date,
                    'project_description': project_description,
                    'responsibilities': responsibilities,
                    'technologies': technologies
                }
            )
            return JsonResponse({'code': 200, 'message': '简历信息保存成功'})
        else:
            print(form.errors)
            return JsonResponse({'code': 400, 'message': '简历信息保存失败'})


def awards(request):
    if request.method == 'GET':
        try:
            info = AwardModel.objects.get(user=request.user)
            form = {
                'award_name': info.award_name,
                'award_level': info.award_level,
                'award_date': info.award_date.strftime('%Y-%m-%d'),
                'award_organization': info.award_organization,
                'description': info.award_description,
            }
        except:
            form = {
                'award_name': '',
                'award_level': '',
                'award_date': '',
                'award_organization': '',
                'description': '',
            }
        return render(request, 'resume_manage/awards.html', {'form': form})
    else:
        form = AwardForm(request.POST)
        if form.is_valid():
            award_name = form.cleaned_data.get('award_name')
            award_level = form.cleaned_data.get('award_level')
            award_date = form.cleaned_data.get('award_date')
            award_organization = form.cleaned_data.get('award_organization')
            award_description = form.cleaned_data.get('award_description')
            AwardModel.objects.update_or_create(
                user=request.user,
                defaults={
                    'award_name': award_name,
                    'award_level': award_level,
                    'award_date': award_date,
                    'award_organization': award_organization,
                    'award_description': award_description
                }
            )
            return JsonResponse({'code': 200, 'message': '简历信息保存成功'})
        else:
            return JsonResponse({'code': 400, 'message': '简历信息保存失败'})


def professional_skills(request):
    if request.method == 'GET':
        try:
            info = SkillModel.objects.get(user=request.user)
            form = {
                'name': info.name,
                'level': info.level,
                'description': info.description,
            }
        except:
            form = {
                'name': '',
                'level': '',
                'description': '',
            }
        return render(request, 'resume_manage/professional_skills.html', {'form': form})
    else:
        # 处理POST请求
        form = SkillForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get('skill_name')
            level = form.cleaned_data.get('skill_level')
            description = form.cleaned_data.get('skill_description')
            SkillModel.objects.update_or_create(
                user=request.user,
                defaults={
                    'name': name,
                    'level': level,
                    'description': description
                }
            )
            return JsonResponse({'code': 200, 'message': '简历信息保存成功'})
        else:
            print(form.errors)
            return JsonResponse({'code': 400, 'message': '简历信息保存失败'})


def job_intentions(request):
    if request.method == 'GET':
        try:
            info = JobIntentionModel.objects.get(user=request.user)
            form = {
                'expected_position': info.expected_position,
                'job_nature': info.job_nature,
                'expected_location': info.expected_location,
                'expected_salary': info.expected_salary,
                'industry': info.industry,
                'join_time': info.join_time,
                'job_description': info.job_description,
            }
        except:
            form = {
                'expected_position': '',
                'job_nature': '',
                'expected_location': '',
                'expected_salary': '',
                'industry': '',
                'join_time': '',
                'job_description': '',
            }
        return render(request, 'resume_manage/job_intentions.html', {'form': form})
    else:
        # 处理POST请求
        form = JobIntentionForm(request.POST)
        if form.is_valid():
            expected_position = form.cleaned_data.get('expected_position')
            job_nature = form.cleaned_data.get('job_nature')
            expected_location = form.cleaned_data.get('expected_location')
            expected_salary = form.cleaned_data.get('expected_salary')
            industry = form.cleaned_data.get('industry')
            join_time = form.cleaned_data.get('join_time')
            job_description = form.cleaned_data.get('job_description')
            JobIntentionModel.objects.update_or_create(
                user=request.user,
                defaults={
                    'expected_position': expected_position,
                    'job_nature': job_nature,
                    'expected_location': expected_location,
                    'expected_salary': expected_salary,
                    'industry': industry,
                    'join_time': join_time,
                    'job_description': job_description
                }
            )
            return JsonResponse({'code': 200, 'message': '简历信息保存成功'})
        else:
            print(form.errors)
            return JsonResponse({'code': 400, 'message': '简历信息保存失败'})


def resume_preview(request):
    if request.method == 'GET':
        # 获取所有已保存的信息
        context = {}
        # 获取基本信息
        try:
            base_info = BaseInformationModel.objects.get(user=request.user)
            context['base_info'] = {
                'name': base_info.name,
                'gender': base_info.gender,
                'birthday': base_info.birthday.strftime('%Y-%m-%d'),
                'phone': base_info.phone,
                'email': base_info.email,
                'location': base_info.location,
                'personal_description': base_info.personal_description,
            }
        except BaseInformationModel.DoesNotExist:
            context['base_info'] = None

        # 获取教育经历
        try:
            edu_info = EducationExperienceModel.objects.get(user=request.user)
            context['education'] = {
                'school': edu_info.school,
                'major': edu_info.major,
                'degree': edu_info.degree,
                'start_date': edu_info.start_date.strftime('%Y-%m-%d'),
                'end_date': edu_info.end_date.strftime('%Y-%m-%d'),
                'gpa': edu_info.gpa,
                'description': edu_info.description,
            }
        except EducationExperienceModel.DoesNotExist:
            context['education'] = None

        # 获取工作经验
        try:
            work_info = WorkExperienceModel.objects.get(user=request.user)
            context['work'] = {
                'company_name': work_info.company_name,
                'position': work_info.position,
                'department': work_info.department,
                'start_date': work_info.start_date.strftime('%Y-%m-%d'),
                'end_date': work_info.end_date.strftime('%Y-%m-%d'),
                'responsibilities': work_info.responsibilities,
            }
        except WorkExperienceModel.DoesNotExist:
            context['work'] = None

        # 获取获奖情况
        try:
            award_info = AwardModel.objects.get(user=request.user)
            context['award'] = {
                'award_name': award_info.award_name,
                'award_level': award_info.award_level,
                'award_date': award_info.award_date.strftime('%Y-%m-%d'),
                'award_organization': award_info.award_organization,
                'award_description': award_info.award_description,
            }
        except AwardModel.DoesNotExist:
            context['award'] = None

        # 获取专业技能
        try:
            skill_info = SkillModel.objects.get(user=request.user)
            context['skill'] = {
                'name': skill_info.name,
                'level': skill_info.level,
                'description': skill_info.description,
            }
        except SkillModel.DoesNotExist:
            context['skill'] = None

        return render(request, 'resume_manage/resume_preview.html', context)



def export_resume_pdf(request):
    # 获取简历数据（与resume_preview视图相同的数据获取逻辑）
    context = {}

    # 获取基本信息
    try:
        base_info = BaseInformationModel.objects.get(user=request.user)
        context['base_info'] = {
            'name': base_info.name,
            'gender': base_info.gender,
            'birthday': base_info.birthday.strftime('%Y-%m-%d'),
            'phone': base_info.phone,
            'email': base_info.email,
            'location': base_info.location,
            'personal_description': base_info.personal_description,
        }
    except BaseInformationModel.DoesNotExist:
        context['base_info'] = None

    # 获取教育经历
    try:
        edu_info = EducationExperienceModel.objects.get(user=request.user)
        context['education'] = {
            'school': edu_info.school,
            'major': edu_info.major,
            'degree': edu_info.degree,
            'start_date': edu_info.start_date.strftime('%Y-%m-%d'),
            'end_date': edu_info.end_date.strftime('%Y-%m-%d'),
            'gpa': edu_info.gpa,
            'description': edu_info.description,
        }
    except EducationExperienceModel.DoesNotExist:
        context['education'] = None

    # 获取工作经验
    try:
        work_info = WorkExperienceModel.objects.get(user=request.user)
        context['work'] = {
            'company_name': work_info.company_name,
            'position': work_info.position,
            'department': work_info.department,
            'start_date': work_info.start_date.strftime('%Y-%m-%d'),
            'end_date': work_info.end_date.strftime('%Y-%m-%d'),
            'responsibilities': work_info.responsibilities,
        }
    except WorkExperienceModel.DoesNotExist:
        context['work'] = None

    # 获取专业技能
    try:
        skill_info = SkillModel.objects.get(user=request.user)
        context['skill'] = {
            'name': skill_info.name,
            'level': skill_info.level,
            'description': skill_info.description,
        }
    except SkillModel.DoesNotExist:
        context['skill'] = None

    # 获取获奖情况
    try:
        award_info = AwardModel.objects.get(user=request.user)
        context['award'] = {
            'award_name': award_info.award_name,
            'award_level': award_info.award_level,
            'award_date': award_info.award_date.strftime('%Y-%m-%d'),
            'award_organization': award_info.award_organization,
            'award_description': award_info.award_description,
        }
    except AwardModel.DoesNotExist:
        context['award'] = None

    # 渲染HTML模板
    html_string = render_to_string('resume_manage/resume_pdf_template.html', context)

    # 生成PDF
    html = HTML(string=html_string, base_url=request.build_absolute_uri())
    pdf = html.write_pdf()

    # 创建HTTP响应
    response = HttpResponse(pdf, content_type='application/pdf')
    filename = f"简历_{context['base_info']['name'] if context['base_info'] else 'unnamed'}.pdf"
    response['Content-Disposition'] = f'attachment; filename="{filename}"'

    return response
